package com.wallet.crypto.trustapp.createWallets;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.blankj.utilcode.util.KeyboardUtils;
import com.wallet.crypto.trustapp.util.Loger;

/**
 * Created by ${张奎勋} on 2018/5/10.
 * 点击空白处关闭键盘
 */
public class ClickHideSoftInput extends RelativeLayout {
    public ClickHideSoftInput(Context context) {
        super(context);
    }

    public ClickHideSoftInput(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ClickHideSoftInput(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                hideKeyboard(ev, findFocus());
                break;
            default:
                break;
        }
        return super.dispatchTouchEvent(ev);
    }


    private void hideKeyboard(MotionEvent event, View view) {
        try {
            if (view != null && view instanceof EditText) {

                int[] location = {0, 0};

                view.getLocationInWindow(location);

                int left = location[0],
                        top = location[1],
                        right = left + view.getWidth(),
                        bottom = top + view.getHeight();

                // 判断焦点位置坐标是否在空间内，如果位置在控件外，则隐藏键盘
                if (event.getRawX() < left || event.getRawX() > right
                        || event.getY() < top || event.getRawY() > bottom) {

                    // 隐藏键盘
                    KeyboardUtils.hideSoftInput(view);
                }
            }
        } catch (Exception ignored) {
            Loger.e("隐藏键盘失败");
        }
    }
}
